//
//  WbPictureViewModel.swift
//  Weibo
//
//  Created by HH on 16/12/7.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

let itemMarign:CGFloat = 5

let itemSizeWidth = (ScreenWidth - 2 * (marign + itemMarign)) / 3

class WbPictureViewModel: NSObject {
    
    //必须要做成单例,不然计算好的图片大小过不去
    static let sharedPictureViewModel = WbPictureViewModel()
    
    var pic_Url:[WbStatusesPictureModel]?{
        
        didSet{
            
            handlePicture(count: pic_Url?.count ?? 0)
           
        }
    }
    
    
    
    //处理PictureView尺寸
    var pictureViewSize:CGSize?
    
    
    //处理配图
    
    private func handlePicture(count:Int) -> () {
        
        if count > 0 {
            
            let col = count > 3 ? 3 : count
            
            let row = (count - 1) / 3 + 1
            
            //处理单张图片
            
            
            if count == 1 {
                
                
                if let imageUrl = pic_Url?.first?.thumbnail_pic {
                    
                    //从下载好缓存的图片中取出对应的图片
                    if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl) {
                        
                        let imageSize = image.size
                        
                        var width:CGFloat = imageSize.width
                        var height:CGFloat = imageSize.height
                        
                        //判断图片宽度是否大于80
                        if imageSize.width < 80 {
                            width = 80
                            
                            height = width / imageSize.width * imageSize.height
                            
                            //判断计算后的高度是否大于150
                            if height > 150 {
                                height = 150
                            }
                            
                        }
                        
                        //计算出经过处理后的图片大小
                        pictureViewSize = CGSize(width: width, height: height)
                        
                    }
                    
                    
                }
                
                return
            }
            
            
            
            
            //处理多张图片
            let pictureViewWidth = CGFloat(col) * itemSizeWidth + CGFloat(col - 1) * itemMarign
            
            let pictureViewHeight = CGFloat(row) * itemSizeWidth + CGFloat(row - 1) * itemMarign
            pictureViewSize = CGSize(width: pictureViewWidth, height: pictureViewHeight)
            
        }else{
            
            //在这里要注意没有图片的情况
            pictureViewSize = CGSize.zero
        }
        
   
        
    }

}
